<template>
  <view class="index-container">
    <!-- 改为左右布局 -->
    <view class="content-box">
      <!-- 左侧分类菜单 -->
      <scroll-view class="category-sidebar" scroll-y>
        <!-- 分类列表 -->
        <view
          class="category-item"
          v-for="(item, index) in categories"
          :key="item.category.id"
          :class="{ active: currentCategoryIndex === index }"
          @tap="switchCategory(index)"
        >
          <view class="category-name">{{ item.category.name }}</view>
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view
        class="product-list"
        scroll-y
        :scroll-top="scrollTop"
        @scroll="onScroll"
        :scroll-with-animation="false"
        refresher-enabled
        @refresherrefresh="onRefresherRefresh"
        ref="productList"
        :refresher-triggered="refresherTriggered"
      >
        <!-- 商品布局 -->
        <view class="products">
          <view 
            class="product-item"
            v-for="goods in currentGoods" 
            :key="goods.id"
            @tap="goToDetail(goods)"
          >
            <!-- 商品图片 -->
            <view class="product-image-wrapper">
              <image class="product-image" :src="goods.picUrl" mode="aspectFill"></image>
              <!-- 标签区域 -->
              <view class="tag new" v-if="goods.isNew">新品</view>
            </view>
            
            <!-- 商品信息 -->
            <view class="product-info">
              <view class="product-title">
                <text class="brand">{{ goods.name.split(' ')[0] }}</text>
                <text class="name">{{ goods.name.split(' ').slice(1).join(' ') }}</text>
              </view>
              <view class="product-brief" v-if="goods.brief">{{ goods.brief }}</view>
              <view class="product-price">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ goods.retailPrice.toFixed(2) }}</text>
                <text v-if="goods.isMultipleSpec" class="starting-price">起</text>
                <text class="original-price" v-if="goods.counterPrice && goods.counterPrice > goods.retailPrice">¥{{ goods.counterPrice.toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 无数据或加载状态 -->
        <view class="empty-products" v-if="currentGoods.length === 0">
          <image src="/static/images/common/empty.png" mode="aspectFit"></image>
          <text>该分类暂无商品</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [],
      currentCategoryIndex: 0,
      scrollTop: 0,
      categoryTops: [],
      isScrolling: false,
      showFilterPanel: false,
      refresherTriggered: false
    }
  },
  
  computed: {
    // 当前分类的商品列表
    currentGoods() {
      if (!this.categories || !this.categories[this.currentCategoryIndex]) {
        return [];
      }
      return this.categories[this.currentCategoryIndex].goodsList || [];
    },
    
    // 当前分类信息
    currentCategory() {
      if (!this.categories || !this.categories[this.currentCategoryIndex]) {
        return null;
      }
      return this.categories[this.currentCategoryIndex].category || null;
    },
    
    // 奇数索引的商品（显示在第一列）
    oddIndexGoods() {
      return this.currentGoods.filter((_, index) => index % 2 === 0);
    },
    
    // 偶数索引的商品（显示在第二列）
    evenIndexGoods() {
      return this.currentGoods.filter((_, index) => index % 2 === 1);
    }
  },
  
  onLoad() {
    this.loadData()
  },

  // 添加下拉刷新
  onPullDownRefresh() {
    this.loadData().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    async loadData() {
      try {
        uni.showLoading({
          title: '加载中'
        });
        const res = await this.$get('catalog/allwithgoods')
        if (res.errno === 0 && res.data) {
          this.categories = res.data
          // 在数据加载完成后，计算每个分类的位置
          this.$nextTick(() => {
            this.calculateCategoryTops()
          })
        } else {
          uni.showToast({
            title: res.errmsg || '获取数据失败',
            icon: 'none'
          })
        }
        uni.hideLoading();
      } catch (error) {
        console.error('获取分类数据失败', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
        uni.hideLoading();
      }
    },
    
    // 添加scroll-view的下拉刷新处理函数
    onRefresherRefresh(e) {
      this.refresherTriggered = true
      this.loadData().then(() => {
        // 停止页面的下拉刷新
        uni.stopPullDownRefresh()
        // 停止scroll-view的下拉刷新状态
        this.refresherTriggered = false
      }).catch(() => {
        // 发生错误时也需要停止刷新状态
        uni.stopPullDownRefresh()
        this.refresherTriggered = false
      })
    },
    
    switchCategory(index) {
      this.currentCategoryIndex = index
      // 滚动到顶部
      this.scrollTop = 0
    },
    
    calculateCategoryTops() {
      const query = uni.createSelectorQuery().in(this)
      query.selectAll('.category-section').boundingClientRect(rects => {
        this.categoryTops = rects.map(rect => rect.top)
      }).exec()
    },
    
    onScroll(e) {
      if (this.isScrolling) return
      
      const scrollTop = e.detail.scrollTop
      // 可以根据需要添加滚动逻辑
    },
    
    goToDetail(goods) {
      uni.navigateTo({
        url: `/pages/product-detail/index?id=${goods.id}`,
        success: (res) => {
          res.eventChannel.emit('sendTestValue', goods)
        }
      })
    },
  }
}
</script>

<style lang="scss">
@import '@/common/mixins.scss';

// 定义新的设计体系色彩 - 简洁风格
$tag-color: #000;         // 新品标签颜色
$text-primary: #333333;      // 主要文字
$text-secondary: #666666;    // 次要文字
$text-light: #999999;        // 浅色文字
$price-color: #000;       // 价格红色
$bg-color: #F5F5F5;          // 背景色
$sidebar-bg: #F5F5F5;        // 侧边栏背景色
$card-bg: #FFFFFF;           // 卡片背景色
$border-color: #EEEEEE;      // 边框颜色

.index-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $bg-color;

  .content-box {
    flex: 1;
    display: flex;
    flex-direction: row;
    overflow: hidden;
    
    // 左侧分类菜单
    .category-sidebar {
      width: 160rpx;
      background-color: $sidebar-bg;
      height: 100vh;
      
      .category-item {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 90rpx;
        position: relative;
        
        .category-name {
          font-size: 24rpx;
          color: $text-secondary;
          font-weight: 400;
          text-align: center;
          padding: 0 10rpx;
          position: relative;
        }

        &.active {
          position: relative;
          background-color: #FFFFFF;
          
          .category-name {
            color: $text-primary;
            font-weight: 600;
            
            &::after {
              content: '';
              position: absolute;
              bottom: -30rpx;
              left: 50%;
              transform: translateX(-50%);
              width: 60rpx;
              height: 10rpx;
              background-color: rgb(0, 0, 0);
              border-radius: 20rpx;
            }
          }
        }
      }
    }
    
    // 右侧商品列表
    .product-list {
      flex: 1;
      overflow: auto;
      background-color: $card-bg;
      
      .products {
        padding: 0;
        
        .product-item {
          display: flex;
          padding: 20rpx;
          background-color: $card-bg;
          border-bottom: 1px solid $border-color;
          margin-bottom: 0;
          position: relative;
          
          .product-image-wrapper {
            position: relative;
            width: 140rpx;
            height: 140rpx;
            flex-shrink: 0;
            margin-right: 20rpx;
            
            .product-image {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            
            .tag {
              position: absolute;
              top: 0;
              right: 0;
              font-size: 20rpx;
              padding: 4rpx 10rpx;
              color: white;
              z-index: 2;
              
              &.new {
                background-color: $tag-color;
              }
            }
          }
          
          .product-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            
            .product-title {
              .brand {
                color: $text-primary;
                font-size: 26rpx;
                font-weight: 600;
                margin-right: 8rpx;
              }
              
              .name {
                color: $text-primary;
                font-size: 26rpx;
              }
            }
            
            .product-brief {
              font-size: 22rpx;
              color: $text-light;
              margin: 10rpx 0;
              @include multi-ellipsis(2);
            }
            
            .product-price {
              display: flex;
              align-items: baseline;
              
              .price-symbol {
                font-size: 22rpx;
                color: $price-color;
              }
              
              .price-value {
                font-size: 26rpx;
                color: $price-color;
              }
              
              .starting-price {
                font-size: 22rpx;
                color: $price-color;
              }
              
              .original-price {
                font-size: 22rpx;
                color: $text-light;
                margin-left: 12rpx;
                text-decoration: line-through;
              }
            }
          }
        }
      }
      
      .empty-products {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100rpx 0;
        
        image {
          width: 200rpx;
          height: 200rpx;
          margin-bottom: 20rpx;
          opacity: 0.7;
        }
        
        text {
          font-size: 26rpx;
          color: $text-light;
        }
      }
    }
  }
}
</style>
